package org.dingfugui.triple.protocol.binary.aio;

import org.dingfugui.triple.common.Logger;
import org.dingfugui.triple.common.LoggerFactory;
import org.dingfugui.triple.connection.Connection;
import org.dingfugui.triple.connection.ConnectionFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created by fugui.ding on 2015/6/10.
 */
public class AioConnectionFactory implements ConnectionFactory {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Connection getConnection(InetSocketAddress address) {

        AsynchronousSocketChannel s;
        try {
            s = AsynchronousSocketChannel.open();
            logger.debug("准备创建连接:{}", address);
            Future<Void> cf = s.connect(address);
            cf.get();
            return new AioConsumerConnection(s);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
